package org.charmsoft.generator;

import cn.hutool.core.io.FileUtil;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.charmsoft.dto.ClassPO;
import org.charmsoft.dto.ClassesInSheet;
import org.charmsoft.dto.ClassesInWorkbook;
import org.charmsoft.error.ReturnCode;
import org.charmsoft.error.StatusCode;
import org.charmsoft.files.DefaultFreemarkerLoader;
import org.charmsoft.files.FreemarkerLoader;
import org.charmsoft.utils.PropertyUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @ Author: Allen J L Chen
 * This Class is to generate class.
 * ${DATE}
 **/
public class ClassGenerator implements Generator{

    private static final Logger LOGGER = LoggerFactory.getLogger(ClassGenerator.class);

    private static Path path = Paths.get("");

    private ClassesInWorkbook classesInWorkbook;

    public ClassGenerator(ClassesInWorkbook classesInWorkbook) {
        this.classesInWorkbook = classesInWorkbook;
    }

    @Override
    public StatusCode generate() {
        return generate(classesInWorkbook);
    }

    public synchronized StatusCode generate(ClassesInWorkbook classesInWorkbook) {
        FreemarkerLoader freemarkerLoader = new DefaultFreemarkerLoader();
        Template template = freemarkerLoader.loadTemplate(PropertyUtils.props.getProperty("POJO"));

        StatusCode statusCode = new StatusCode();
        try {
            StringWriter stringWriter= new StringWriter();
            for(ClassesInSheet classesInSheet: classesInWorkbook.getClassesInWorkbookMap().values()){
                String sPath = path.toAbsolutePath().toString()+ "/output/"+ classesInWorkbook.getProjectName()+ "/"+ classesInSheet.getWorksheetName() + "/";
                if(!FileUtil.isDirectory(sPath)) {
                    FileUtil.mkdir(sPath);
                }
                for (ClassPO classPO: classesInSheet.getClassPOMap().values()) {
                    template.process(classPO, stringWriter);
                    stringWriter.flush();
                    FileOutputStream fos = new FileOutputStream(sPath + classPO.getName()+".java");
                    OutputStreamWriter osw = new OutputStreamWriter(fos);
                    BufferedWriter bfw = new BufferedWriter(osw);
                    template.process(classPO, bfw);
                    osw.close();
                }
            }
            statusCode.setMessage(String.valueOf(ReturnCode.valueOf(ReturnCode.CONVERTED.name())));
        } catch (IOException | TemplateException e) {
            LOGGER.error(e.getStackTrace().toString());
            statusCode.setMessage(e.getMessage());
        }
        return statusCode;
    }


}
